﻿using Core.DomainServices;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.DomainServices
{
    public class Word2Pdf : IDocumentConversion
    {
        public Microsoft.Office.Interop.Word.Document wordDoc { get; set; }
        private Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

        public void ConvertTo(IList<string> files)
        {
            object missing = Type.Missing;
            foreach (var item in files)
            {
                try
                {
                    wordDoc = wordApp.Documents.Open(item, ReadOnly: false, Visible: false);
                    wordDoc = wordApp.Documents.Open(item, ref missing, false,
                                          ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref missing,
                                          ref missing, ref missing, false,
                                          ref missing, ref missing, ref missing, ref missing);

                    string pdfFile = item.Replace(".docx", ".pdf");
                    wordDoc.ExportAsFixedFormat(pdfFile, WdExportFormat.wdExportFormatPDF);
                }

                catch (Exception ex)
                {
                    Console.WriteLine("Exception Caught: " + ex.Message);
                }
                finally
                {

                    if (wordDoc != null)
                    {
                        wordDoc.Close(WdSaveOptions.wdDoNotSaveChanges);
                    }                    
                }
            }
            if (wordApp != null)
            {
                wordApp.Quit(WdSaveOptions.wdDoNotSaveChanges);
                wordApp = null;
            }
        }

        public void Dispose()
        {
            try
            {
                ((_Application)wordApp).Quit(SaveChanges: false, OriginalFormat: false, RouteDocument: false);

                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
                Marshal.ReleaseComObject(wordApp);
                wordApp = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            catch { }
        }
    }
}
